import { useRect } from "@vant/use";
import { loadImageAsync } from "./util.mjs";
import { noop } from "../../utils/index.mjs";
import { h } from "vue";
var stdin_default = (lazyManager) => ({
  props: {
    src: [String, Object],
    tag: {
      type: String,
      default: "img"
    }
  },
  render() {
    var _a, _b;
    return h(
      this.tag,
      {
        src: this.renderSrc
      },
      (_b = (_a = this.$slots).default) == null ? void 0 : _b.call(_a)
    );
  },
  data() {
    return {
      el: null,
      options: { // 接收外部src或者整体配置参数
        src: "",
        error: "",
        loading: "",
        attempt: lazyManager.options.attempt // 加载失败重试次数
      },
      state: { // 组件内部状态 在lazyClass中observerHandler 使用
        loaded: false,
        error: false,
        attempt: 0
      },
      renderSrc: "" // 实际渲染展示的图片src
    };
  },
  watch: {
    src() {
      this.init();
      lazyManager.addLazyBox(this);
      lazyManager.lazyLoadHandler();
    }
  },
  created() {
    this.init();
  },
  mounted() {
    // 传递el 在lazy.js中统一使用
    this.el = this.$el;
    lazyManager.addLazyBox(this);
    // 初次或修改src已在可视区域直接执行??
    lazyManager.lazyLoadHandler();
  },
  beforeUnmount() {
    lazyManager.removeComponent(this);
  },
  methods: {
    init() { // 重置相关状态
      const { src, loading, error } = lazyManager.valueFormatter(this.src);
      this.state.loaded = false;
      this.options.src = src;
      this.options.error = error;
      this.options.loading = loading;
      this.renderSrc = this.options.loading;
    },
    checkInView() {
      const rect = useRect(this.$el);
      return rect.top < window.innerHeight * lazyManager.options.preLoad && rect.bottom > 0 && rect.left < window.innerWidth * lazyManager.options.preLoad && rect.right > 0;
    },
    // 视口及事件监听会多次触发
    load(onFinish = noop) {
      // 当尝试次数超出时,打印相关信息
      if (this.state.attempt > this.options.attempt - 1 && this.state.error) {
        if (process.env.NODE_ENV !== "production" && !lazyManager.options.silent) {
          console.log(
            `[@vant/lazyload] ${this.options.src} tried too more than ${this.options.attempt} times`
          );
        }
        onFinish();
        return;
      }
      const { src } = this.options;
      loadImageAsync(
        { src },
        ({ src: src2 }) => {
          this.renderSrc = src2;
          this.state.loaded = true;
        },
        () => {
          this.state.attempt++;
          this.renderSrc = this.options.error;
          this.state.error = true;
        }
      );
    }
  }
});
export {
  stdin_default as default
};
